<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/17
 * Time: 15:01
 * Description: 微信用户模型
 */
namespace app\api\logic;

use app\api\exception\ApiException;
use app\api\model\WechatUser;
use plugin\saiadmin\basic\BaseLogic;
use Tinywan\Jwt\JwtToken;
use app\api\logic\CollectionLogic;

class WechatUserLogic extends BaseLogic {

    public function __construct() {
        $this->model = new WechatUser();
    }
    /**
     * 通过微信登录
     * @param $data
     * @return array
     */
    public function loginByWechat($data):array{
        $user=$this->model->where(['openid'=>$data['openid']])->findOrEmpty();
       
        $token='';
        $userInfo=[];
        if(!$user->isEmpty()){
            $user->last_login_time = date('Y-m-d H:i:s');
            $user->login_ip = request()->getRealIp();
            $user->save();
             $token = JwtToken::generateToken([
            'id' => $user->user_id,
            'nickname' => $user->nickname,
            'type' => JwtToken::TOKEN_CLIENT_MOBILE
        ]);
            $userInfo=$user;
            $collectionLogic=new CollectionLogic();
            $user_collection=$collectionLogic->getMe($user->user_id);
            $userInfo['policy_num']=$user_collection[1]??0;
            $userInfo['supply_demand_num']=$user_collection[2]??0;
            $userInfo['talents_num']=$user_collection[3]??0;
            $userInfo['space_num']=$user_collection[4]??0;
        }
       
        return [
            'token' => $token,
            'user'  => $userInfo,
            'openid'=>$data['openid']
        ];
    }
  public function regesterUser($data): array{
        $user=$this->model->where(['openid'=>$data['openid']])->findOrEmpty();
         if(!$user->isEmpty()){
            throw new ApiException('用户已注册请勿重复注册');
         }
        $data['register_time'] = $data['last_login_time'] = date('Y-m-d H:i:s');
        $data['login_ip'] = request()->getRealIp();
        $user = $this->model->create($data);
        $token = JwtToken::generateToken([
            'id' => $user->user_id,
            'nickname' => $user->nickname,
            'type' => JwtToken::TOKEN_CLIENT_MOBILE
        ]);
        return [
            'token' => $token,
            'user'  => $user->toArray(), // 修正变量引用错误
            'openid' => $data['openid']
        ];
    }

}